package zgc.demo.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import zgc.demo.consumer.entity.Goods;
import zgc.demo.consumer.service.OrderService;

import java.util.List;

@RestController
@RequestMapping("/order2")
public class OrderController02 {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;


    /**
     * 使用注册中心获取服务名称对应的ip+port结合rest实现远程接口调用
     * 这样做的好处是：ip+port不必写死
     *
     * @param goodsId
     * @return
     */
    @GetMapping("/getGoodsById/{goodsId}")
    public Goods getGoodsById(@PathVariable("goodsId") String goodsId) {
        //1.获取服务列表,即ip+port注册列表,因为可能微服务是集群模式，所以获取的是集合，而不是单一
        List<ServiceInstance> provider = discoveryClient.getInstances("PROVIDER");

        //2.获取微服务实例
        ServiceInstance serviceInstance = provider.get(0);

        //3.获取微服务的ip+port
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();

        //4.动态创建url
        String url = "http://" + host + ":" + port + "/goods/getGoodsById/" + goodsId;

        //5.远程接口请求
        return restTemplate.getForObject(url, Goods.class);

    }

}
